import { Navigate, useLocation } from 'react-router-dom'
import routes from './index'
// 自定义路由守卫
// children： 子组件
// 构造路由白名单

const routesMeta = routes.reduce((map: RoutesMetaRecord, item) => {
    map[item.path] = item.meta
    if (item.children) {
        item.children.forEach(val => {
            map[val.path] = val.meta
        })
    }
    return map
}, {})

export function RouterGuard({ children }: { children: any }) {
    const location = useLocation()
    // const [searchParams] = useSearchParams()
    const { pathname } = location
    if (routesMeta[pathname as keyof typeof routesMeta]?.isLogin) {
        alert('您还没有登录， 请先登录')
        return <Navigate to={'/login'}></Navigate>
    }
    document.title = routesMeta[pathname as keyof typeof routesMeta]?.title
    return children
}